package com.example.ywj.toutiao;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ywj.toutiao.compoents.MyGlideEngine;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.ImageUtil;
import com.example.ywj.toutiao.utils.IssueAdapter;
import com.example.ywj.toutiao.utils.MyEmojiAdapter;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.example.ywj.toutiao.utils.SpUtils;
import com.example.ywj.toutiao.utils.Util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hb.dialog.myDialog.MyAlertDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class IssueActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "IssueActivity";
    @BindView(R.id.issue_back)
    public TextView issue_back;
    @BindView(R.id.issue_pic)
    public GridView issue_pic;
    @BindView(R.id.issue_warn)
    public TextView issue_warn;
    @BindView(R.id.add_content)
    public EditText add_content;
    @BindView(R.id.issue_fabu)
    public TextView issue_fabu;
    @BindView(R.id.issue_jianpan)
    public TextView issue_jianpan;
    @BindView(R.id.issue_biaoqing)
    public TextView issue_biaoqing;
    @BindView(R.id.issue_bianqing_panel)
    public LinearLayout issue_bianqing_panel;
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
    public Boolean flag1 = true;
    public Boolean flag2 = true;
    private AlertDialog dialog;
    public IssueAdapter issueAdapter;
    private List<Uri> list = new ArrayList<>();
    @BindView(R.id.issue_biaoqing_gridview)
    public GridView issue_biaoqing_gridview;
    private String baseUrl = Constant.BASEURL;
    public int emojis[] = {R.string.emoji1,R.string.emoji2,R.string.emoji3,R.string.emoji4,R.string.emoji5,R.string.emoji6,R.string.emoji7,R.string.emoji8,R.string.emoji9,R.string.emoji33,R.string.emoji10,R.string.emoji11,R.string.emoji12,R.string.emoji13,R.string.emoji14,R.string.emoji15,R.string.emoji16,R.string.emoji17,R.string.emoji18,R.string.emoji19,R.string.emoji20,R.string.emoji21,R.string.emoji22,R.string.emoji23,R.string.emoji24,R.string.emoji25,R.string.emoji26,R.string.emoji27,R.string.emoji28,R.string.emoji29,R.string.emoji30,R.string.emoji31,R.string.emoji32,R.string.emoji34,R.string.emoji35,R.string.emoji36,R.string.emoji37,R.string.emoji38,R.string.emoji39,R.string.emoji40,R.string.emoji41,R.string.emoji42,R.string.emoji43,R.string.emoji44,R.string.emoji45,R.string.emoji46,R.string.emoji47,R.string.emoji48,R.string.emoji49,R.string.emoji50,R.string.emoji51,R.string.emoji52,R.string.emoji53,R.string.emoji54,R.string.emoji55,R.string.emoji56,R.string.emoji57,R.string.emoji58,R.string.emoji59,R.string.emoji60,R.string.emoji61,R.string.emoji62,R.string.emoji63,R.string.emoji64,R.string.emoji65,R.string.emoji66,R.string.emoji67,R.string.emoji68,R.string.emoji69,R.string.emoji70,R.string.emoji71,R.string.emoji72,R.string.emoji73,R.string.emoji74,R.string.emoji75,R.string.emoji76,R.string.emoji77,R.string.emoji78,R.string.emoji79,R.string.emoji80};


    public List<Integer> listEmoji = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_issue);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//因为不是所有的系统都可以设置颜色的，在4.4以下就不可以。。有的说4.1，所以在设置的时候要检查一下系统版本是否是4.1以上
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.trgray));
        }
        ButterKnife.bind(this);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            int flag1 = ContextCompat.checkSelfPermission(this,permissions[0]);
            int flag2 = ContextCompat.checkSelfPermission(this,permissions[1]);
            if(flag1!=PackageManager.PERMISSION_GRANTED||flag2!=PackageManager.PERMISSION_GRANTED){
                showDialogTipUserRequestPermission();
            }
        }
        initView();
    }
    public void initView(){
        issue_back.setOnClickListener(this);
        issueAdapter = new IssueAdapter(list);
        issue_pic.setAdapter(issueAdapter);
        //add_content.requestFocus();
        //flag1 = true;
        add_content.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.i(TAG, "onFocusChange: "+hasFocus);
                if(hasFocus){
                    //flag1 = true;
                    issue_bianqing_panel.setVisibility(View.GONE);
                }
            }
        });
        add_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(!add_content.getText().toString().equals("")){
                    issue_fabu.setTextColor(getResources().getColor(R.color.colorAccent));
                }else{
                    issue_fabu.setTextColor(getResources().getColor(R.color.native_color));
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        issue_pic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == parent.getChildCount() - 1){
                    addImage();
                }
            }
        });
       issue_fabu.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               String username = SpUtils.getString(v.getContext(),"username");
               if(add_content.getText().toString().equals("")&&!username.equals("")){
                   Toasty.info(v.getContext(),"请先输入内容",Toasty.LENGTH_LONG).show();
                   return;
               }else if(username.equals("")){
                   Intent intent = new Intent(IssueActivity.this,LoginActivity.class);
                   finish();
                   startActivity(intent);
               }else if(!add_content.getText().toString().equals("")&&!username.equals("")){
                   //Toasty.info(v.getContext(),"可以发布" ,Toasty.LENGTH_LONG).show();
                   upload();
               }
           }
       });
        Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        issue_jianpan.setTypeface(font);
        issue_biaoqing.setTypeface(font);
        issue_jianpan.setText(getResources().getString(R.string.jianpang));
        issue_biaoqing.setText(getResources().getString(R.string.biaoqing));
        issue_jianpan.setOnClickListener(this);
        issue_biaoqing.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(!flag2){
                    add_content.clearFocus();
                    issue_bianqing_panel.setVisibility(View.GONE);
                    Util.hideKeyboard(IssueActivity.this);
                    flag1 = true;
                    flag2 = true;
                }else {
                    add_content.clearFocus();
                    issue_bianqing_panel.setVisibility(View.VISIBLE);
                    Util.hideKeyboard(IssueActivity.this);
                    flag1 = true;
                    flag2 = false;
                }

            }
        });
        for(int i = 0;i<emojis.length;i++){
            listEmoji.add(emojis[i]);
        }
        MyEmojiAdapter myEmojiAdapter = new MyEmojiAdapter(listEmoji);
        issue_biaoqing_gridview.setAdapter(myEmojiAdapter);
        issue_biaoqing_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = view.findViewById(R.id.item_emoji);
                add_content.setText(add_content.getText().append(tv.getText().toString().trim()));
            }
        });
    }
    public void showDialogTipUserRequestPermission(){
        MyAlertDialog myAlertDialog = new MyAlertDialog(this).builder()
                .setTitle("存储权限")
                .setMsg("是否开启权限")
                .setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startRequestPermission();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        myAlertDialog.show();
    }
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
                      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                          //Log.i(TAG, "onRequestPermissionsResult: "+grantResults[0]);
                                 if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                                     finish();
                                  } else {
                                        Toasty.success(this, "权限获取成功", Toasty.LENGTH_SHORT).show();
                                    }
                            }
                     }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.issue_back:
                SpUtils.putBoolean(IssueActivity.this,"isreturn",false);
                Intent intent = new Intent(IssueActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(0,R.anim.translate_dialog_out);
                break;
            case R.id.issue_jianpan:
                if(!flag1){
                    add_content.clearFocus();
                    issue_bianqing_panel.setVisibility(View.GONE);
                    Util.hideKeyboard(IssueActivity.this);
                    flag1 = true;
                    flag2 = false;
                }else{
                    add_content.clearFocus();
                    issue_bianqing_panel.setVisibility(View.GONE);
                    Util.showKeyBoard(add_content);
                    flag1 = false;
                    flag2 = true;
                }
        }
    }
    public void addImage(){
        Matisse
                .from(IssueActivity.this)
                //选择视频和图片
                .choose(MimeType.ofAll())
                //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                .capture(true)
                .captureStrategy(new CaptureStrategy(true,"PhotoPicker"))
                //有序选择图片 123456...
                .countable(true)
                //最大选择数量为9
                .maxSelectable(9)
                //选择方向
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                //界面中缩略图的质量
                .thumbnailScale(0.8f)
                //蓝色主题
                .theme(R.style.Matisse_Zhihu)
                //Glide加载方式
                .imageEngine(new MyGlideEngine())
                //请求码
                .forResult(200);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            List<Uri> pathList = Matisse.obtainResult(data);
            list.addAll(pathList);
            if(list.size()>=9){
                issue_warn.setVisibility(View.VISIBLE);
            }else {
                issue_warn.setVisibility(View.GONE);
            }
            issueAdapter.notifyDataSetChanged();

        }
    }

    public void upload(){
        if(list.size() == 0){
            Toasty.info(IssueActivity.this,"请选择图片").show();
        }else{
            //Log.i(TAG, "upload: "+2);
            HashMap<String, RequestBody> map = new HashMap<>();
            for(int i=0;i<list.size();i++) {
                try{
                    //Bitmap photoBmp = getBitmapFormUri()
                   //Log.i(TAG, "upload: "+3);
                    File file = new File(ImageUtil.getRealFilePath(IssueActivity.this,list.get(i)));
                    //Log.i(TAG, "upload: "+file);
                    map.put("file\"; filename=\"image"+i+".jpg\"", RequestBody.create(MediaType.parse("multipart/form-data"), file));
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                ResponseApi responseApi = retrofit.create(ResponseApi.class);
                String username = SpUtils.getString(IssueActivity.this,"username");
                RequestBody requestBody1 = RequestBody.create(MediaType.parse("text/plain"), add_content.getText().toString());
                RequestBody requestBody2 = RequestBody.create(MediaType.parse("text/plain"),username);
                Call<ResponseBody> call = responseApi.uploadFiles(map,requestBody1,requestBody2);
                Log.i(TAG, "upload: "+4);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Log.i(TAG, "onResponse: "+3);
                        String json = null;
                        try {
                            json = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.i(TAG, "onResponse: "+json);
                        JsonObject obj = (JsonObject) new JsonParser().parse(json);
                        Integer code = obj.get("statusCode").getAsInt();
                        if(code == 200&&obj.has("data")){
                            Toasty.success(IssueActivity.this,"发布成功，刷新可以查看",Toasty.LENGTH_LONG).show();
                            SpUtils.putBoolean(IssueActivity.this,"isreturn",false);
                            Intent intent = new Intent(IssueActivity.this,MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.i(TAG, "onFailure: "+t);
                    }
                });

            }

        }

}
